package chatServer;

import java.net.*;
import java.io.*;

import messenger.Message;

public class ChatServer {
	
	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {

		if(args.length==0){
			System.out.println("missing option -start or -showlog");
			System.exit(0);
		}
		ServerSocket serverSocket = null;
		boolean listening = true;
		int port = 4444;
		double ver = 1.5;
		ConversDB db = new ConversDB();
		
		
			
		for(String i :args){
			if(i.contains("-start"))
			{
				try {
					serverSocket = new ServerSocket(4444);
					//System.setErr(err);
				} catch (IOException e) {
					System.err.println("Could not listen on port: " + port);
					System.exit(-1);
				}

				System.err.println("ChatServer " + ver + " started at "+serverSocket.getLocalSocketAddress()+" on port " + port);
				while (listening)
					new ChatServerThread(serverSocket.accept(), db,false).start();

				serverSocket.close();
				db.saveState();
			}
			if(i.contains("-showlog"))
				for(UserDB u : db.getUsers())
					if(db.getMessagelog().containsKey(u))
						for(Message l : db.getMessagelog().get(u).getMessages())
							System.out.println(l.getDate().getTime().toString()+" "+l.getFrom()+"  -> "+l.getTo()+" ("+l.getBody()+")");
		}
		
		
	
		
	
	}
}